package cn.kailangtu.dataspot.camera;

import android.util.Log;
import android.view.SurfaceHolder;
import androidx.annotation.NonNull;

import cn.kailangtu.commontools.APPSPUtils;
import cn.kailangtu.commontools.AppUtils;
import cn.kailangtu.dataspot.status;
import cn.kailangtu.dataspot.widget.AvcPlayer;

public class AvcPlayerHelper {
    String TAG = "AvcPlayerHelper";
    private SurfaceHolder surfaceHolder;
    private AvcPlayer avcPlayer;
    SmIpCamera smIpCamera;
    private int RTSP_MS = 0;
    private boolean isOpen = false;
   // private String urlRTSP = "rtsp://192.168.1.10:8554/profile0";
    private String urlRTSP =  "rtsp://"+ APPSPUtils.getInstance().getCameraIp()+":8554/profile0";
    public void initIPCameraView(AvcPlayer avcPlayer){
        this.avcPlayer = avcPlayer;
//        String localCameraIp = AppUtils.getIpCameraUrl();
//        if(localCameraIp != null && !localCameraIp.isEmpty())
//        {
//            this.urlRTSP = localCameraIp;
//        }
        surfaceHolder = avcPlayer.getHolder();
        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                Log.d(TAG,"surfaceCreated");
                cshAVCSmail1();
            }
            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                Log.d(TAG,"surfaceChanged");
            }
            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                Log.d(TAG,"surfaceDestroyed");
                avcPlayer.stopPreview();
            }
        });
    }

    private void cshAVCSmail1(){
        Log.d(TAG,"cshAVC1");

        avcPlayer.init(avcPlayer.getWidth(), avcPlayer.getHeight(), new AvcPlayer.Callback() {
            @Override
            public void onFrameUpdate(byte[] frame) {
            }
        });
        avcPlayer.startPreview();
        smIpCamera = new SmIpCamera("1", urlRTSP, RTSP_MS, 25, avcPlayer);
        openCamera();
    }

    private void openCamera(){
        //showSmDialog("正在打开2号相机...");
        Log.d(TAG,"openCamera1");
        smIpCamera.openCamera(new SmIpCamera.CallbackIpcCamOpen() {
            @Override
            public void onOpenSuc(int errCode) {
                isOpen = true;
            }
            @Override
            public void onOpenFai(int errCode) {
            }
        });
    }

    public void pause(boolean isPause)
    {
        if(smIpCamera != null) {
            smIpCamera.setPause(isPause);
        }

    }

    public void close(){
        if(isOpen)
        {
            smIpCamera.CloseCamera();
        }
    }
}
